package core.hmxchen.log.formatter;

import core.hmxchen.log.RequestLogFormatter;
import core.hmxchen.log.entity.MethodInfo;
import core.hmxchen.log.enums.Level;
import core.hmxchen.log.handler.LogHandler;
import org.slf4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * RequestLogPrintFormatter
 * TODO
 * 请求日志打印
 * @author hmxchen
 * @version v1.0.0
 * @date 2021/9/12 20:07
 */
public class RequestLogPrintFormatter implements RequestLogFormatter {
    @Override
    public void format(Logger log, Level level, String busName, MethodInfo methodInfo, Object[] args, String[] filterParamNames, Object result, Throwable throwable) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n【请求路径】:").append("【"+request.getRequestURL().toString()+"】");
        String method = request.getMethod();
        if(!StringUtils.isEmpty(method)){
            stringBuilder.append("\n【请求类型】:").append("【"+method+"】");
        }
        stringBuilder.append("\n【IP地址】:").append("【"+request.getRemoteAddr()+"】");
        stringBuilder.append(LogHandler.getAroundInfo(busName,methodInfo,args,filterParamNames,result,throwable));
        LogHandler.print(log,level,stringBuilder.toString());
        if(throwable!=null){
            log.error(throwable.getMessage(),throwable);
        }
    }
}
